<?php

/***
 * Class SendMsg
 * 微网通联 - 乐信通
 * 接入微网通，下面是他们家的模版接口
 */
class SendMsg
{
    const LMOBILE_SNAME = 'dlrenduan';
    const LMOBILE_SPWD = 'Huohuojiang2018';
    const LMOBILE_SPRD_ID = '1012888';  //短信验证消息
    const LMOBILE_NOTICE_ID = '1012808';  //通知消息模版
    const LMOBILE_URL = 'http://cf.51welink.com/submitdata/Service.asmx/g_Submit'; //微网通链接

    #拼接参数
    protected static function makeParams($mobile, $content, $id){
        return "sname=" . self::LMOBILE_SNAME . "&spwd=" . self::LMOBILE_SPWD . "&scorpid=&sprdid=" . $id . "&sdst=" . $mobile . "&smsg=" . rawurlencode($content);
    }

    # 通知消息模版
    public static function LmobilenoticeSms($mobile, $content = '')
    {
        if (empty($content) || empty($mobile)) {
            return false;
        }
        $data = self::makeParams($mobile, $content, self::LMOBILE_NOTICE_ID);
        $ret = self::curlPost($data, self::LMOBILE_URL);
        return $ret;
    }


    #验证短信模版
    public static function LmobileSms($mobile, $content = '')
    {
        if (empty($content) || empty($mobile)) {
            return false;
        }
        $data = self::makeParams($mobile, $content, self::LMOBILE_SPRD_ID);
        $ret = self::curlPost($data, self::LMOBILE_URL);
        return $ret;
    }

    static function makeHearder($url_info, $data){
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader .= "Host:" . $url_info['host'] . "\r\n";
        $httpheader .= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader .= "Content-Length:" . strlen($data) . "\r\n";
        $httpheader .= "Connection:close\r\n\r\n";
        $httpheader .= $data;

        return $httpheader;
    }

    static function sock($url_info, $httpheader){
        $fd = fsockopen($url_info['host'], 80);
        fwrite($fd, $httpheader);
        $ret = "";
        while (!feof($fd)) {
            $ret .= fread($fd, 128);
        }
        fclose($fd);
        if ($ret != '') {
            $start = strpos($ret, '<?xml');
            if ($start > 0) {
                $ret = substr($ret, $start);
            }
        }

        return $ret;
    }

    static function curlPost($data, $target)
    {
        $url_info = parse_url($target);
        $httpheader = self::makeHearder($url_info, $data);
        $gets = self::sock($url_info, $httpheader);
        return $gets;
    }
}